

require 'net/http'
require 'net/https'
require 'uri'

module Provider

  class CoopCH < AbstractProvider

    @sms_sender

    @own_number
    @login_name

    def initialize(sms_sender)
      @sms_sender = sms_sender

      @login_name = @sms_sender.get_main.login_name
      @own_number = @sms_sender.get_main.own_number
    end

    def send(to, text)
      
      own_number = @own_number
      use_ssl = 0

      #trans =Iconv.new('ISO-8859-1','UTF-8') # new converter-object encoding from UTF-8 to ISO-8859-1
      text=URI.escape(text) # convert message to ISO-8859-1 and escape it for use in URL

      #SmsWidget::Main.logger.debug "coop.ch, text: #{text}"


      # URLs
      send_url = 'http://www2.coop.ch/coopmobile/sms.cfm?language=de'

      # Settings
      user_agent = "Coop.ch SMS Widget"
      cookie = ''
      if use_ssl
        port = 443
      else
        port = 80
      end

      to_prefix = to[0..2]
      to_number = to[3..9]
      from_prefix = own_number[0..2]
      from_number = own_number[3..9]

      SmsWidget::Main.logger.debug "to_prefix: #{to_prefix}\nto_number: #{to_number}"

      # Now we can send the message
      send_uri = URI.parse(send_url)

      http = Net::HTTP.new(send_uri.host, port)
      http.use_ssl = use_ssl
      post_data = "maxCounts=30&gensms=true&sms_myCode=#{@login_name}&sms_sender_prefix=#{from_prefix}&sms_sender_number=#{from_number}&sms_recipient_prefix=#{to_prefix}&sms_recipient_number=#{to_number}&sms_text=#{text}&accept_agb=1"
      post_headers = { 'Referer' =>  send_url, 'Cookie' => cookie, 'Content-Type' => 'application/x-www-form-urlencoded'}

      resp, data = http.post(send_uri.path, post_data, post_headers)
      #SmsWidget::Main.logger.debug "coop ch resp: #{resp}"
      if data.include? "Sie haben heute bereits 5 Free SMS verschickt."
        raise TooManySmsSentException
      else
        sms_sent()
      end
      #data.each { |line|
      #  if line =~ /successOutput/
      #    #exit 0
      #    sms_sent()
      #    sent = true
      #  end
      #}
      #unless sent
      #  sms_not_sent("")
      #end

      #SmsWidget::Main.logger.debug "coop ch data: #{data}"
      #sms_sent()
    end

  end

end
